package com.gok.einvoice.web.utils;

import com.gok.einvoice.common.exception.ServiceException;
import com.gok.einvoice.framework.web.service.Invoice;
import com.gok.einvoice.web.dto.HotelInvoiceDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 自定义基础工具类
 */
@Component
public class BaseUtils {

    /**
     * 将Invoice转化为HotelInvoiceDTO集合
     * @param invoice
     * @return
     */
    public HotelInvoiceDTO invoiceToHotelInvoiceDTO(Invoice invoice, Integer userId) {
        if (ObjectUtils.isEmpty(invoice)) {
            return null;
        }

        //获取住宿信息列表
        List<Invoice.Detail> detailList = invoice.getDetailList();
        if (CollectionUtils.isEmpty(detailList) || detailList.size() != 1) {
            //没有住宿信息
            throw new ServiceException("非酒店发票");
        }

        //有住宿数据
        Invoice.Detail detail = detailList.get(0);
        return HotelInvoiceDTO.builder()
                .userId(userId)
                .hotelName(invoice.getSellerName())
                .days(detail.getCount().intValue())
                .unitPrice(String.valueOf(detail.getPrice()))
                .invoiceValue(String.valueOf(invoice.getTotalAmount()))
                .invoicingDate(BaseUtils.stringToLocalDate(invoice.getDate()))
                .invoiceNumber(invoice.getNumber())
                .taxRate(String.valueOf(detail.getTaxRate()))
                .sellerName(invoice.getSellerName())
                .build();
    }

    /**
     * String（xxxx年xx月xx日类型）转localDate
     * @param date
     * @return
     */
    private static LocalDate stringToLocalDate(String date) {
        if (!StringUtils.hasText(date)) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        return LocalDate.parse(date, formatter);
    }
}
